package cas.ihep.hdfs;

import com.google.common.io.Closer;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.protocol.ClientDatanodeProtocol;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;

import java.io.Closeable;
import java.io.IOException;

/**
 * Created by gesturewei on 17-3-24.
 */
public abstract class HdfsBlock implements java.io.Closeable{

    protected HdfsFile mParent;
    protected boolean mClosed;
    protected Closer mCloser;
    protected LocatedBlock mBlock;
    protected ClientDatanodeProtocol mDatanodeClient;

    protected HdfsBlock(HdfsFile parent,LocatedBlock mblck)throws IOException {
        mParent=parent;
        mClosed=false;
        mCloser= Closer.create();
        mBlock=mblck;
        DatanodeInfo locations[]=mblck.getLocations();
        for (DatanodeInfo loc:locations){
            if (HdfsSystem.LOCALHOST_ADDRESS.equals(loc.getIpAddr())){
                mDatanodeClient= DFSUtil.createClientDatanodeProtocolProxy(loc,parent.mFs.mConfig,0,false);
                if (mDatanodeClient instanceof Closeable) {
                    mCloser.register((Closeable) mDatanodeClient);
                }
                break;
            }
        }
    }

    public void close()throws IOException {
        if (!mClosed){
            mCloser.close();
            mClosed=true;
        }
    }

    public long blockSize(){ return mBlock.getBlockSize();}

    public long blockId(){
        return mBlock.getBlock().getBlockId();
    }

    public boolean isLocal(){
        return mDatanodeClient!=null;
    }

    public abstract String getBlockPath()throws IOException;
}
